package com.ic.loan.http

import com.blankj.utilcode.util.*
import com.ic.loan.activity.LoginActivity
import com.ic.loan.cache.Constant
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import org.json.JSONObject
import java.io.File
import java.util.*

object HttpUtils {
    private var params: HttpParams? = null
    fun postOkGo(
        map: MutableMap<String, Any>,
        url: String?,
        listener: ResultListener,
        showSuccessMsg: Boolean = false
    ) {
        if (!map.isNullOrEmpty()) {
            map["sign"] = encodeSign(map)
        }
        params = mapParse(map)
        OkGo.post<String>(url)
            .apply {
                val token = SPUtils.getInstance().getString(Constant.TOKEN)
                if (!token.isNullOrBlank()) {
                    headers("token", token)
                }
            }
            .params(params)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    try {
                        var json = response?.body()
                        val jsonObject = JSONObject(json)
                        val status = jsonObject.optInt("code")
                        if (status == 200) {
                            if (jsonObject.has("data")) {
                                listener.onSucceeded(
                                    jsonObject.get("data").toString()
                                )
                                if (showSuccessMsg) {
                                    jsonObject.getString("msg")?.apply {
                                        ToastUtils.showShort(this)
                                    }
                                }
                            }
                        } else if (status == 440) {
                            //跳转到登录页面
                            if (ActivityUtils.getTopActivity() !is LoginActivity) {
                                ActivityUtils.startActivity(LoginActivity::class.java)
                            }
                        } else {
                            listener.onFailed(jsonObject.getString("msg"))
                        }
                    } catch (e: Exception) {
                        listener.onErr(e.toString())
                    }

                    listener.onLoadFinish()
                }

                override fun onError(response: Response<String>) {
                    super.onError(response)
                    listener.onErr(response.exception.message)
                    /*跳转到登录页面*/
                    if (ActivityUtils.getTopActivity() !is LoginActivity) {
                        ActivityUtils.startActivity(LoginActivity::class.java)
                    }
                    listener.onLoadFinish()
                    ToastUtils.showShort("error")
                }
            })
    }


    fun postOkGoForUpdataFile(
        map: MutableMap<String, Any>,
        fileName: String?,
        file: File?,
        url: String?,
        listener: ResultListener
    ) {
        if (!map.isNullOrEmpty()) {
            map["sign"] = encodeSign(map)
        }
        params = mapParse(map)
        params!!.put(fileName,file)
        OkGo.post<String>(url)
            .params(params)
            .apply {
                val token = SPUtils.getInstance().getString(Constant.TOKEN)
                if (!token.isNullOrBlank()) {
                    headers("token", token)
                }
            }
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    try {
                        var json = response?.body()
                        val jsonObject = JSONObject(json)
                        val status = jsonObject.optInt("code")
                        if (status == 200) {
                            if (jsonObject.has("data")) {
                                listener.onSucceeded(
                                    jsonObject.get("data").toString()
                                )
                            }
                        } else if (status == 440) {
                            //跳转到登录页面
                            if (ActivityUtils.getTopActivity() !is LoginActivity) {
                                ActivityUtils.startActivity(LoginActivity::class.java)
                            }
                        } else {
                            listener.onFailed(jsonObject.getString("msg"))
                        }
                    } catch (e: Exception) {
                        listener.onErr(e.toString())
                    }
                    listener?.onLoadFinish()
                }
                override fun onError(response: Response<String>) {
                    super.onError(response)
                    listener?.onLoadFinish()
                }
            })
    }

    fun postOkGoForFile(
        map: Map<String, Any>,
        pic: File?,
        files: List<File?>?,
        url: String?,
        listener: ResultListener?
    ) {
        params = mapParse(map)
        OkGo.post<String>(url)
            .params(params)
            .addFileParams("file", files)
            .params("pic", pic)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {}
                override fun onError(response: Response<String>) {
                    super.onError(response)
                }
            })
    }


    fun encodeSign(inputMap: Map<String, Any>): String {
        val appKey = "H4W81N02CY"
        val comparator = kotlin.Comparator { key1: String, key2: String -> key1.compareTo(key2) }
        val map = TreeMap<String, Any>(comparator)
        map.putAll(inputMap)
        var stringBuffer = StringBuffer()
        map.keys.forEach {
            stringBuffer.append("$it=${map[it]}     ")
        }
        val string = "${stringBuffer.toString().trim().replace("     ", "&")}|$appKey"
        LogUtils.d("sign == $string")
        return EncryptUtils.encryptMD5ToString(string).toLowerCase()
    }

    //将map放到params
    private fun mapParse(map: Map<String, Any>): HttpParams {
        val params = HttpParams()
        val entryIterator = map.entries.iterator()
        while (entryIterator.hasNext()) {
            val entry = entryIterator.next()
            params.put(entry.key, entry.value.toString())
        }
        return params
    }
}